<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CPaymentInvoiceForm">
          <a-row>
            <a-divider >项目信息</a-divider >

            <a-col :span="12">
              <a-form-item label="项目" v-bind="validateInfos.projectId" id="CPaymentInvoiceForm-projectId" name="projectId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.projectId"
                  :showSearch="true"
                  :options="projectList"
                  optionFilterProp="label"
                  @change="loadSubProjectList"
                ></a-select>
              </a-form-item>
            </a-col>


            <a-col :span="12" >
              <a-form-item label="子项目" v-bind="validateInfos.subProjectId" id="CPaymentInvoiceForm-subProjectId" name="subProjectId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.subProjectId"
                  :showSearch="true"
                  :options="subProjectList"
                  optionFilterProp="label"
                ></a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12" >
              <a-form-item label="总包主体" v-bind="validateInfos.companyInfoId" id="CPaymentInvoiceForm-companyInfoId" name="companyInfoId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.companyInfoId"
                  :showSearch="true"
                  :options="companyInfoList"
                  optionFilterProp="label"
                ></a-select>
              </a-form-item>
            </a-col>


            <a-col :span="12">
              <a-form-item label="发票名称" v-bind="validateInfos.title" id="CPaymentInvoiceForm-title" name="title">
                <a-input v-model:value="formData.title" placeholder="请输入发票名称"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="发票文件" v-bind="validateInfos.invoiceFile" id="CPaymentInvoiceForm-invoiceFile" name="invoiceFile">
								<j-upload v-model:value="formData.invoiceFile" dragger="true"   :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }"  ></j-upload>
							</a-form-item>
						</a-col>

            <a-divider >发票信息</a-divider >
            <a-col :span="8">
              <a-form-item label="发票号码" v-bind="validateInfos.invoiceNumber" id="CPaymentInvoiceForm-invoiceNumber" name="invoiceNumber">
                <a-input v-model:value="formData.invoiceNumber" placeholder="请输入发票号码"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="发票类型" v-bind="validateInfos.invoiceType" id="CPaymentInvoiceForm-invoiceType" name="invoiceType">
                <a-input v-model:value="formData.invoiceType" placeholder="请输入发票类型"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="开票日期" v-bind="validateInfos.invoiceDate" id="CPaymentInvoiceForm-invoiceDate" name="invoiceDate">
                <a-date-picker placeholder="请选择开票日期"  v-model:value="formData.invoiceDate" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
              </a-form-item>
            </a-col>

            <a-divider >开票信息</a-divider >
						<a-col :span="6">
							<a-form-item label="项目名称" v-bind="validateInfos.projectName" id="CPaymentInvoiceForm-projectName" name="projectName">
								<a-input v-model:value="formData.projectName" placeholder="请输入项目名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="6">
              <a-form-item label="金额" v-bind="validateInfos.amount" id="CPaymentInvoiceForm-amount" name="amount">
                <a-input-number v-model:value="formData.amount" placeholder="请输入金额" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="税率/征收率" v-bind="validateInfos.taxRate" id="CPaymentInvoiceForm-taxRate" name="taxRate">
                <a-input-number v-model:value="formData.taxRate" placeholder="请输入税率/征收率" style="width: 100%" />
              </a-form-item>
            </a-col>

						<a-col :span="6">
							<a-form-item label="税额" v-bind="validateInfos.taxAmount" id="CPaymentInvoiceForm-taxAmount" name="taxAmount">
								<a-input-number v-model:value="formData.taxAmount" placeholder="请输入税额" style="width: 100%" />
							</a-form-item>
						</a-col>

            <a-col :span="12">
              <a-form-item label="价税合计（小写）" v-bind="validateInfos.totalAmountWithTax" id="CPaymentInvoiceForm-totalAmountWithTax" name="totalAmountWithTax">
                <a-input-number v-model:value="formData.totalAmountWithTax" placeholder="请输入价税合计（小写）" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="价税合计（大写）" v-bind="validateInfos.totalAmountWithTaxUpper" id="CPaymentInvoiceForm-totalAmountWithTaxUpper" name="totalAmountWithTaxUpper">
                <a-input v-model:value="formData.totalAmountWithTaxUpper" placeholder="请输入价税合计（大写）"  allow-clear ></a-input>
              </a-form-item>
            </a-col>


            <a-divider >销售采购方信息</a-divider >
            <a-col :span="12">
              <a-form-item label="销售方名称" v-bind="validateInfos.sellerName" id="CPaymentInvoiceForm-sellerName" name="sellerName">
                <a-input v-model:value="formData.sellerName" placeholder="请输入销售方名称"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="销售方统一社会信用代码/纳税人识别号" v-bind="validateInfos.sellerTaxId" id="CPaymentInvoiceForm-sellerTaxId" name="sellerTaxId">
                <a-input v-model:value="formData.sellerTaxId" placeholder="请输入销售方统一社会信用代码/纳税人识别号"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="购买方名称" v-bind="validateInfos.buyName" id="CPaymentInvoiceForm-buyName" name="buyName">
                <a-input v-model:value="formData.buyName" placeholder="请输入购买方名称"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="购买方统一社会信用代码/纳税人识别号" v-bind="validateInfos.buyTaxId" id="CPaymentInvoiceForm-buyTaxId" name="buyTaxId">
                <a-input v-model:value="formData.buyTaxId" placeholder="请输入购买方统一社会信用代码/纳税人识别号"  allow-clear ></a-input>
              </a-form-item>
            </a-col>

            <a-col :span="24">
              <a-form-item label="开票人" v-bind="validateInfos.invoicer" id="CPaymentInvoiceForm-invoicer" name="invoicer">
                <a-input v-model:value="formData.invoicer" placeholder="请输入开票人"  allow-clear ></a-input>
              </a-form-item>
            </a-col>

            <a-col :span="24">
              <a-form-item label="备注" v-bind="validateInfos.remarks" id="CPaymentInvoiceForm-remarks" name="remarks">
                <a-textarea v-model:value="formData.remarks" :rows="4" placeholder="请输入备注" />
              </a-form-item>
            </a-col>


          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../CPaymentInvoice.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { getCompanyInfoList, getProjectList, getSubProjectList } from '@/views/common.api';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    request: '',   
    projectId: undefined,
    subProjectId: undefined,
    invoiceFile: '',   
    invoiceStatus: '',   
    projectName: '',   
    taxAmount: undefined,
    invoiceDate: '',   
    invoicer: '',   
    invoiceType: '',   
    totalAmountWithTax: undefined,
    taxRate: undefined,
    totalAmountWithTaxUpper: '',   
    remarks: '',   
    invoiceNumber: '',   
    amount: undefined,
    sellerName: '',   
    sellerTaxId: '',   
    buyName: '',   
    buyTaxId: '',
    title:'',
    companyInfoId:undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    projectId: [{ required: true, message: '请输入项目!'},],
    subProjectId: [{ required: true, message: '请输入子项目!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add(record) {
    edit(record);
  }

  /**
   * 编辑
   */
  function edit(record) {
    loadProjectList()
    if(record != undefined ){
      if(record.projectId != undefined &&
        record.projectId != null){
        loadSubProjectList(record.projectId);
      }
    }


    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }
  /**
   * 加载 主项目下拉
   */
  const projectList = ref([])
  async function loadProjectList(){
    projectList.value = []
    projectList.value = await getProjectList()
  }
  /**
   * 加载 子主项目 下拉
   */
  const subProjectList = ref([])
  async function loadSubProjectList(projectId){
    formData.subProjectId=undefined
    formData.companyInfoId=undefined
    subProjectList.value = []
    const params = {'projectId':projectId}
    subProjectList.value = await getSubProjectList(params)
    loadCompanyList(projectId)
  }

  /**
   * 加载 总包商
   */
  const companyInfoList = ref([])
  async function loadCompanyList(projectId){
    companyInfoList.value = []
    const params = {'projectId':projectId}
    companyInfoList.value = await getCompanyInfoList(params)
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
